package com.example.zookpeeper.controller;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

@RestController
public class ZookpeerController {

    @Autowired
    private CuratorFramework curatorFramework;

    /**
     * 创建ZKNdoe
     *
     * @return
     */
    @RequestMapping("/createZKNode")
    public String createZKNode() {
        String createZKNode = null;
        try {

            createZKNode = curatorFramework.create().forPath("/createZKNode", "onese".getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return createZKNode;
    }

    /**
     * 读取节点
     */
    @RequestMapping("/getZKNode")
    public String getZKNode(@RequestParam("path") String path) throws Exception {
        Stat stat = curatorFramework.checkExists().forPath(path);
        String result = null;
        if (stat != null) {
            result = new String(curatorFramework.getData().forPath(path));
        } else {
            result = curatorFramework.create().forPath(path, "rertyy".getBytes());
        }
        return result;
    }

    /**
     * ZK ID生成器
     */
    @RequestMapping("/getZKCreateID")
    public String getZKCreateID() throws Exception {
        String destPath = curatorFramework.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath("/createZKNode");

        return destPath;
    }


}


